/**
 * 健康检查工具
 * 提供系统运行状态监控和诊断端点
 */
const os = require('os');
const { exec } = require('child_process');
const schedule = require('node-schedule');
const logger = require('./logger');

// 系统资源使用情况
let systemStatus = {
  status: 'online',
  uptime: 0,
  lastCheck: new Date(),
  memory: {
    total: 0,
    free: 0,
    usage: 0
  },
  cpu: {
    load: 0,
    usage: 0
  },
  services: {
    database: 'unknown',
    whatsapp: 'unknown'
  }
};

// 更新系统资源使用状态
const updateSystemStatus = () => {
  const now = new Date();
  const totalMemory = os.totalmem();
  const freeMemory = os.freemem();
  
  systemStatus.uptime = process.uptime();
  systemStatus.lastCheck = now;
  systemStatus.memory = {
    total: Math.round(totalMemory / 1024 / 1024),
    free: Math.round(freeMemory / 1024 / 1024),
    usage: Math.round((1 - freeMemory / totalMemory) * 100)
  };
  systemStatus.cpu.load = os.loadavg()[0];
  
  // 在Linux/macOS上获取CPU使用率
  if (os.platform() !== 'win32') {
    exec('top -bn1 | grep "Cpu(s)" | sed "s/.*, *\\([0-9.]*\\)%* id.*/\\1/" | awk \'{print 100 - $1}\'', (error, stdout) => {
      if (!error) {
        systemStatus.cpu.usage = parseFloat(stdout.trim());
      }
    });
  } else {
    // Windows平台上使用PowerShell获取CPU使用率
    exec('powershell "Get-Counter \\"\\\\Processor(_Total)\\\\% Processor Time\\" | Select-Object -ExpandProperty CounterSamples | Select-Object -ExpandProperty CookedValue"', (error, stdout) => {
      if (!error) {
        systemStatus.cpu.usage = parseFloat(stdout.trim());
      }
    });
  }
  
  // 记录系统资源状态
  if (systemStatus.memory.usage > 85 || systemStatus.cpu.usage > 90) {
    logger.warn('系统资源使用过高', {
      memory: systemStatus.memory,
      cpu: systemStatus.cpu
    });
  }
  
  return systemStatus;
};

// 检查数据库连接
const checkDatabaseConnection = async () => {
  try {
    const mongoose = require('mongoose');
    if (mongoose.connection.readyState === 1) {
      systemStatus.services.database = 'online';
    } else {
      systemStatus.services.database = 'offline';
      logger.error('MongoDB连接已断开');
    }
  } catch (error) {
    systemStatus.services.database = 'error';
    logger.error('检查数据库连接时出错', error);
  }
};

// 检查WhatsApp服务状态
const checkWhatsAppService = async () => {
  try {
    const whatsappService = require('../services/whatsappService');
    const status = whatsappService.getConnectionStatus();
    
    systemStatus.services.whatsapp = status.status || 'unknown';
    
    if (status.status !== 'connected') {
      logger.warn('WhatsApp服务不在线', { status: status.status });
    }
  } catch (error) {
    systemStatus.services.whatsapp = 'error';
    logger.error('检查WhatsApp服务时出错', error);
  }
};

// 定时健康检查任务
const setupHealthCheckSchedule = () => {
  // 每分钟检查一次系统状态
  schedule.scheduleJob('*/1 * * * *', async () => {
    try {
      updateSystemStatus();
      await checkDatabaseConnection();
      await checkWhatsAppService();
      
      // 如果存在严重问题，发送警报
      if (systemStatus.services.database === 'offline' || 
          systemStatus.services.whatsapp === 'error' ||
          systemStatus.memory.usage > 95) {
        
        logger.error('系统健康检查警报', systemStatus);
        
        // 可以在这里添加发送警报的代码，如发送邮件或短信通知
      }
    } catch (error) {
      logger.error('执行健康检查时出错', error);
    }
  });
  
  logger.info('健康检查计划已设置');
};

// 初始化健康检查
const initialize = (app) => {
  // 首次更新状态
  updateSystemStatus();
  
  // 设置健康检查端点
  app.get('/api/health', (req, res) => {
    updateSystemStatus();
    res.json(systemStatus);
  });
  
  // 设置详细健康检查端点（需要认证）
  app.get('/api/health/detailed', async (req, res) => {
    try {
      await checkDatabaseConnection();
      await checkWhatsAppService();
      updateSystemStatus();
      
      // 添加额外的系统信息
      const detailedStatus = {
        ...systemStatus,
        system: {
          platform: os.platform(),
          type: os.type(),
          release: os.release(),
          arch: os.arch(),
          hostname: os.hostname(),
          cpus: os.cpus().length,
          networkInterfaces: os.networkInterfaces()
        },
        process: {
          pid: process.pid,
          title: process.title,
          versions: process.versions,
          memoryUsage: process.memoryUsage()
        }
      };
      
      res.json(detailedStatus);
    } catch (error) {
      logger.error('获取详细健康信息时出错', error);
      res.status(500).json({
        status: 'error',
        message: '获取健康信息时出错',
        error: process.env.NODE_ENV === 'development' ? error.message : undefined
      });
    }
  });
  
  // 设置健康检查计划
  setupHealthCheckSchedule();
  
  logger.info('健康检查系统已初始化');
};

module.exports = {
  initialize,
  updateSystemStatus,
  getSystemStatus: () => systemStatus,
  checkDatabaseConnection,
  checkWhatsAppService
}; 